{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "import xlwings as xw\n",
    "import random\n",
    "app=xw.App(visible=False,add_book=False)  #后台运行Excel\n",
    "app.display_alerts=False   #不显示Excel消息框\n",
    "app.screen_updating=False  #关闭屏幕更新,可加快宏的执行速度\n",
    "wb = xw.Book(\"XX公司1~3月序时账.xls\") ##导入Excel文件\n",
    "sheet = wb.sheets[\"序时账\"] ##导入工作表名“序时账”\n",
    "info = sheet.used_range # 读取excel中的最大行\n",
    "max_row =info.last_cell.row# 读取excel中的最大行\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "将抽取样本数为： 25 个\n",
      "凭证号为： ['记-0019', '记-0025', '记-0030', '记-0025', '记-0039', '记-0026', '记-0042', '记-0019', '记-0044', '记-0021', '记-0011', '记-0024', '记-0023', '记-0040', '记-0021', '记-0001', '记-0025', '记-0048', '记-0047', '记-0001', '记-0013', '记-0002', '记-0032', '记-0033', '记-0008']\n"
     ]
    }
   ],
   "source": [
    "## 按要求进行样本数判断，Excel大于250行的话，抽25个样本，小于250又大于100的抽15个样本。\n",
    "\n",
    "if max_row >= 250:\n",
    "    sample_number = 25\n",
    "elif max_row < 250 and max_row >= 100 :\n",
    "    sample_number = 15\n",
    "elif max_row < 100 and max_row >= 50 :\n",
    "    sample_number = 10\n",
    "elif max_row < 50 and max_row >= 12 :\n",
    "    sample_number = 4\n",
    "elif max_row < 12 and max_row >= 4 :\n",
    "    sample_number = 2\n",
    "elif max_row < 4 :\n",
    "    sample_number = 1\n",
    "print(\"将抽取样本数为：\",sample_number,\"个\") \n",
    "list = sheet.range(f'b1:b{max_row}').value ##导入凭证号的这一列\n",
    "random.seed(max_row)  ##设置种子\n",
    "slice=random.sample(list,sample_number)## 按列抽取指定样本数量\n",
    "print(\"凭证号为：\",slice)\n",
    "new_wb=xw.Book()##新建新工作簿\n",
    "new_sheet=new_wb.sheets.add()##新工作表\n",
    "new_sheet['A1'].value=slice  #将结果保存在新表\n",
    "new_wb.save(r'抽样结果.xlsx')##保存\n",
    "wb.close()\n",
    "new_wb.close()\n",
    "app.quit()\n",
    "\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
